// CNodeClient.cpp: implementation of the CNodeClient class.
//
//////////////////////////////////////////////////////////////////////

#include "CNodeClient.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


CNodeClient::CNodeClient(std::string ipAddress, int port){
	this->port = port;
	this->ipAddress = ipAddress;
}
CNodeClient::CNodeClient()
{

}

CNodeClient::~CNodeClient()
{

}

void CNodeClient::conectar(){
	WSADATA wsaData; /* Utilizada para inicializacion del winsock */
	WORD wVersionReq = MAKEWORD(2, 2); /* Contiene la version */
	SOCKET sock; /* Contiene la informacion del socket */
	struct hostent* hostInfo; /* Se utiliza para convertir el nombre del host a su direccion IP */
	struct sockaddr_in sockAddrIn; /* Direccion de socket */
	int codError = 0; /* Codigo de error que se evalua dentro de la funcion */
	
	/* Inicializa el socket */
	codError = WSAStartup(wVersionReq, &wsaData);
	if (codError != 0) {
		//resultado = RES_ERROR_STARTUP;
		IOException ex("RES_ERROR_STARTUP");
		throw ex;
	} else {
		/* Crea un socket */
		sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		u_long iMode = 0;
		ioctlsocket(csocket, FIONBIO, &iMode);
		if (sock == INVALID_SOCKET) {
			//resultado = RES_INVALID_SOCKET;
			IOException ex("RES_INVALID_SOCKET");
			throw ex;
        } else {
			/* Carga los valores de sockAddrIn */
			sockAddrIn.sin_family = AF_INET;       /* Protocolo ipv4 */
			sockAddrIn.sin_port = htons(this->port);   /* Puerto indicado */
			hostInfo = gethostbyname(this->ipAddress.c_str());  /* Direccion IP */
			sockAddrIn.sin_addr = *((struct in_addr *)((*hostInfo).h_addr));
			codError = connect(sock, (SOCKADDR *)(&sockAddrIn), sizeof(sockAddrIn));
            if (codError != 0) {
				//exception
               //resultado = RES_ERROR_CONNECT;
			   IOException ex("RES_ERROR_CONNECT");
				throw ex;
            } else {
				this->csocket = sock;
				this->in.setSocket(this->csocket);
				this->out.setSocket(this->csocket);
            }

      }
   }
}